package com.xidian.zhiancloud.service.emergencyManagement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.emergencyManagement.EmergencyTeamManagementDTO;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.emergencyManagement.EmergencyTeamManagementDTOVO;
import com.xidian.zhiancloud.vo.emergencyManagement.EmergencyTeamManagementVO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.qo.emergencyManagement.EmergencyTeamManagementQO;
import com.xidian.zhiancloud.vo.emergencyManagement.PersonnelInformationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EmergencyTeamManagementService extends ServiceImpl<EmergencyTeamManagementMapper, EmergencyTeamManagement> implements IService<EmergencyTeamManagement> {


    @Autowired
    private EmergencyTeamManagementMapper emergencyTeamManagementMappper;

    @Autowired
    private PersonnelInformationMapper personnelInformationMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysJobMapper sysJobMapper;

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean add(EmergencyTeamManagementDTO emergencyTeamManagementDTO) {
        EmergencyTeamManagement emergencyTeamManagement = emergencyTeamManagementDTO.getEmergencyTeamManagement();
        int result = emergencyTeamManagementMappper.insert(emergencyTeamManagement);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        int count = 0;
        for(int i=0;i<emergencyTeamManagementDTO.getPersonnelInformationList().size();i++){
            emergencyTeamManagementDTO.getPersonnelInformationList().get(i).setEmergencyTeamId(emergencyTeamManagementDTO.getEmergencyTeamManagement().getId());
            personnelInformationMapper.insert(emergencyTeamManagementDTO.getPersonnelInformationList().get(i));
            count++;
        }
        if (count != emergencyTeamManagementDTO.getPersonnelInformationList().size()) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
//        for (PersonnelInformation personnelInformation : emergencyTeamManagementDTO.getPersonnelInformationList()) {
//            personnelInformation.setEmergencyTeamId(emergencyTeamManagementDTO.getEmergencyTeamManagement().getId());
//            int tmp = personnelInformationMapper.insert(personnelInformation);
//            if (tmp == 0) {
//                throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
//            }
//        }
        return true;
    }

    public EmergencyTeamManagementDTOVO getById(Long id) {
        EmergencyTeamManagement emergencyTeamManagement = emergencyTeamManagementMappper.selectById(id);
        if (emergencyTeamManagement == null) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        //修改为mybatis plus的条件查询
        QueryWrapper<PersonnelInformation> personnelInformationQueryWrapper = new QueryWrapper<PersonnelInformation>();
        personnelInformationQueryWrapper.eq("emergency_team_id",id);
        List<PersonnelInformation> personnelInformationList=personnelInformationMapper.selectList(personnelInformationQueryWrapper);

        EmergencyTeamManagementDTOVO res=new EmergencyTeamManagementDTOVO();
        EmergencyTeamManagementVO vo=new EmergencyTeamManagementVO();
        BeanUtils.copyProperties(emergencyTeamManagement,vo);
        SysUser adder= sysUserMapper.selectById(vo.getAdderId());
        vo.setAdderName(adder==null?"该用户不存在":adder.getName());
        Organization org = organizationMapper.selectById(vo.getOrganizationId());
        vo.setOrganizationName(org==null?"该部门不存在":org.getName());
        res.setEmergencyTeamManagementVO(vo);

        List<PersonnelInformationVO> voList=new LinkedList<>();
        for(int i=0;i<personnelInformationList.size();i++){
            PersonnelInformationVO vos=new PersonnelInformationVO();
            BeanUtils.copyProperties(personnelInformationList.get(i),vos);
            SysUser userid =sysUserMapper.selectById(vos.getUserId());
            vos.setPersonnelName(userid==null?"该用户不存在":userid.getName());
            String ids_s=userid.getOrgids();
            long[] ids_l = Arrays.stream(ids_s.split(",")).mapToLong(Long::parseLong).toArray();

            List<String> names = Arrays.stream(ids_l).mapToObj(tmp_id -> {
                Organization p_org = organizationMapper.selectById(tmp_id);
                return p_org == null ? "该部门已被删除" : p_org.getName();
            }).collect(Collectors.toList());

            vos.setOrganizationNames(StringUtils.concatStrings(names));
//            vos.setOrganizationName(userid==null?"该用户不存在":userid.getOrgname());
            vos.setTel(userid==null?"该用户不存在":userid.getPhone());
            voList.add(vos);
        }
        res.setPersonnelInformationvoList(voList);
        return res;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean deleteByIds(Long[] ids) {
        int res = 0;
        int res2 = 0;
        for (int i = 0; i < ids.length; i++) {
            //mybatis plus的条件删除
            LambdaQueryWrapper<PersonnelInformation> personnelInformationLambdaQueryWrapper= Wrappers.<PersonnelInformation>lambdaQuery();
            personnelInformationLambdaQueryWrapper.eq(PersonnelInformation::getEmergencyTeamId,ids[i]);
            res+=personnelInformationMapper.delete(personnelInformationLambdaQueryWrapper);
            res2 += emergencyTeamManagementMappper.deleteById(ids[i]);
        }
        if (res == 0 || res2 == 0) {
            return false;
        }
        return true;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean patchById(EmergencyTeamManagementDTO emergencyTeamManagementDTO) {
        EmergencyTeamManagement emergencyTeamManagement = emergencyTeamManagementDTO.getEmergencyTeamManagement();
        List<PersonnelInformation> list = emergencyTeamManagementDTO.getPersonnelInformationList();
        int result = emergencyTeamManagementMappper.updateById(emergencyTeamManagement);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        LambdaQueryWrapper<PersonnelInformation> personnelInformationLambdaUpdateWrapper=Wrappers.<PersonnelInformation>lambdaQuery();
        personnelInformationLambdaUpdateWrapper.eq(PersonnelInformation::getEmergencyTeamId,emergencyTeamManagement.getId());
        personnelInformationMapper.delete(personnelInformationLambdaUpdateWrapper);
        list.forEach(detail -> {
            detail.setEmergencyTeamId(emergencyTeamManagement.getId());
            personnelInformationMapper.insert(detail);
        });
        return true;
    }

    public IPage<EmergencyTeamManagementVO> getListByQO(EmergencyTeamManagementQO emergencyTeamManagementQO) {
        Page<EmergencyTeamManagementVO> page = new Page<>(emergencyTeamManagementQO.getCurrent(), emergencyTeamManagementQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("add_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<EmergencyTeamManagementVO> ans= emergencyTeamManagementMappper.getListByQO(page,emergencyTeamManagementQO);
        for (EmergencyTeamManagementVO record : ans.getRecords()) {
            Long id = record.getOrganizationId();
            Organization org = organizationMapper.selectById(record.getOrganizationId());
            record.setOrganizationName(org==null?"该部门不存在":org.getName());
            SysUser userid =sysUserMapper.selectById(record.getAdderId());
            record.setAdderName(userid==null?"该用户不存在":userid.getName());
        }
        return ans;
    }
}
